using System;
using System.IO;
using System.Text;

namespace libraw
{
	public class IOCursor
	{
		public IOCursor ( string file, IOPermission permissions )
		{
			FileName = file;
			Permission = permissions;
			
			try
			{
				if ( Permission == IOPermission.Read )
				{
					m_reader = new BinaryReader( new StreamReader( FileName ).BaseStream );
					Length = (ulong)m_reader.BaseStream.Length;
				}
				else
				{
					m_writer = new BinaryWriter( new StreamWriter( FileName ).BaseStream );
					Length = (ulong)m_writer.BaseStream.Length;
				}
			}
			catch( Exception e )
			{
				throw new InvalidOperationException(
					string.Format("{0} failed construction due to: {1}", typeof(IOCursor), e.Message));
			}
		}
		
		private BinaryReader m_reader;
		private BinaryWriter m_writer;
		
		public string FileName
		{
			get;
			private set;
		}
		
		public IOPermission Permission
		{
			get;
			private set;
		}
		
		public ulong Length
		{
			get;
			private set;
		}
		
		public ulong Position
		{
			get
			{
				if ( Permission == IOPermission.Read )
				{
					return (ulong)m_reader.BaseStream.Position;
				}
				else
				{
					return (ulong)m_writer.BaseStream.Position;
				}
			}
			
			set
			{
				if ( value > long.MaxValue ) 
					throw new InvalidOperationException(
						string.Format("Tried to set value {0}, which is larger than long.max", value));
				
				if ( value > (ulong)Length )
					throw new InvalidOperationException(
						string.Format("Tried to set value {0}, which is past the end of the stream at {1}", value, Length));
				
				if ( Permission == IOPermission.Read )
				{
					m_reader.BaseStream.Position = (long)value;
				}
				else
				{
					m_writer.BaseStream.Position = (long)value;
				}
			}
		}
		
		#region Reading
		
		#endregion
		
		#region Writing
		
		#endregion
	}
	
	public enum IOPermission
	{
		Read,
		Write,
	}
}

